<template>
  <div class="msg-table flex flex-column">
    <div class="msg-type flex-fixed">
      <span class="msg-type-label">消息类型-大类：</span>
      <radio-button-group
        v-model="formData.big_type"
        :options="[{ label: '所有', value: '' }].concat(bigTypeList)"
        @change="(val) => typeChange(val, 'big')"
      />
    </div>
    <div class="msg-type flex-fixed">
      <span class="msg-type-label">消息类型-小类：</span>
      <radio-button-group
        v-model="formData.small_type"
        :options="[{ label: '所有', value: '' }].concat(smallList)"
        @change="(val) => typeChange(val, 'small')"
      />
    </div>
    <div class="msg-type flex-fixed">
      <span class="msg-type-label">消息类型-细类：</span>
      <radio-button-group
        v-model="formData.fine_type"
        :options="[{ label: '所有', value: '' }].concat(fineList)"
        @change="typeChange('', 'fine')"
      />
    </div>
    <antd-form
      ref="AntdForm"
      v-model="formData"
      :options="formOptions"
      @submit="formSubmit"
      class="flex-fixed"
      style="padding: 15px"
    />
    <common-table
      class="flex-auto-height"
      ref="table"
      :show-toolbar="false"
      @vue:mounted="() => $refs.table.load()"
      :fetch="getDataAsync"
      :fetch-params="paramsData"
      :columns="columns"
      :checkboxConfig="{ checkField: 'isChecked' }"
      @checkbox-all="selectChangeEvent"
      @checkbox-change="selectChangeEvent"
    >
      <template #table-checkbox v-if="status == 'unread'">
        <vxe-column type="checkbox" width="60" align="center" />
      </template>
      <template #title="{ text, scope }">
        {{ text || scope.source || '-' }}
      </template>
      <template #action="{ scope }">
        <a-button type="link" @click="details(scope)">查看</a-button>
      </template>
    </common-table>
    <div class="bottom-btn flex-fixed" v-if="status == 'unread'">
      <a-button @click="markMultiMsgAsRead">批量标记已读</a-button>
      <a-button @click="clearMsg">全部标记已读</a-button>
    </div>
  </div>
</template>

<script>
import { dialog } from '@gis/lib/components/antd-dialog';
import { showDeviceWarnDialog, showYanGanWarnDialog } from '../../warn-dialog/index.js';

import get from 'lodash-es/get.js';
import isEmpty from 'lodash-es/isEmpty.js';
import { msgList, msgNoticeDic, msgNoticeRead, msgNoticeAllRead, getDicListByName } from '@gis/lib/api';
import { useUserInfoStore } from '@gis/lib/pinia/userInfo.js';
import { useDicDataStore } from '@gis/lib/pinia/dicData.js';
import { getEnumList } from '@gis/lib/enums';
import { Modal } from 'ant-design-vue';
import { openEventDetailsDialog } from '../../../views/event-manage/event-opt.js';
import { openInstructionDetailsDialog } from '../../../views/instruction/dialog.js';

const date = 'YYYY-MM-DD HH:mm:ss';
const typeEnum = { unread: 0, read: 1 };

export default {
  name: 'msg-table-list',
  components: {},
  props: {
    status: {
      type: String,
      default: 'unread',
      validator: (v) => Object.keys(typeEnum).indexOf(v) > -1,
    },
  },
  setup() {
    const userInfoStore = useUserInfoStore();
    const dicDataStore = useDicDataStore();
    const { accountId } = userInfoStore;
    return { accountId, userInfoStore, dicDataStore };
  },
  data() {
    return {
      dicObj: {},
      typeObj: {
        big: {},
        small: {},
      },
      smallList: [],
      fineList: [],
      columns: [
        { title: '标题', dataIndex: 'title' },
        {
          title: '类型',
          dataIndex: 'big_type',
          customRender: (v, scope) =>
            `${v ? this.dicObj[v] : '-'}${scope.small_type ? (v ? '/' : '') + this.dicObj[scope.small_type] : ''}${
              scope.fine_type ? (scope.small_type ? '/' : '') + this.dicObj[scope.fine_type] : ''
            }`,
        },
        { title: '内容', dataIndex: 'content' },
        { title: '时间', dataIndex: 'create_time' },
        { title: '操作', width: 100, scopedSlots: { customRender: 'action' } },
      ],
      formData: {
        big_type: '',
        small_type: '',
        fine_type: '',
      },
      selectedRowKeys: [],
    };
  },
  computed: {
    formOptions() {
      return [
        {
          component: 'a-range-picker',
          field: 'start_time,end_time',
          label: '时间段',
          props: { showTime: true, valueFormat: 'YYYY-MM-DD HH:mm:ss' },
        },
        /*{
          component: 'a-select',
          label: '大类',
          field: 'big_type',
          props: {
            allowClear: true,
            options: this.bigTypeList,
            onChange: (v) => {
              // this.$refs.AntdForm.update('small_type', undefined);
              // this.$refs.AntdForm.update('fine_type', undefined);
              this.typeChange(v, 'big');
            },
          },
        },
        {
          component: 'a-select',
          label: '小类',
          field: 'small_type',
          props: {
            allowClear: true,
            options: this.smallList,
            onChange: (v) => {
              // this.$refs.AntdForm.update('fine_type', undefined);
              this.typeChange(v, 'small');
            },
          },
        },
        {
          component: 'a-select',
          label: '细类',
          field: 'fine_type',
          props: {
            allowClear: true,
            options: this.fineList,
          },
        },*/
        {
          component: 'a-select',
          label: '消息级别',
          field: 'message_level',
          props: {
            allowClear: true,
            options: getEnumList('msgLevel'),
          },
        },
      ];
    },
    bigTypeList() {
      return this.dicDataStore.getDicDataList('D0137');
    },
    paramsData() {
      return Object.assign(
        {
          message_people_id: this.accountId,
          status: typeEnum[this.status],
        },
        this.formData
      );
    },
  },
  created() {
    this.getDicAsync();
  },
  methods: {
    selectChangeEvent(data) {
      // console.log('点击一个', data.checked, data);
      this.selectedRowKeys = get(data, 'records', []).map((item) => item.id);
    },
    formSubmit(val) {
      this.formData = Object.assign({}, this.formData, val);
      this.$refs.table.load();
    },
    async typeChange(v, type) {
      if (type == 'big') {
        this.smallList = [];
        this.fineList = [];
        this.formData = Object.assign({}, this.formData, { small_type: '', fine_type: '' });
      }
      if (type == 'small') {
        this.fineList = [];
        this.formData = Object.assign({}, this.formData, { fine_type: '' });
      }
      this.$nextTick(() => {
        this.$refs.table.load(); // 更新表格
      });
      if (!v) return false;
      if (!isEmpty(this.typeObj[type][v])) {
        this[type == 'big' ? 'smallList' : 'fineList'] = this.typeObj[type][v];
        return;
      }
      let { data = [] } = await getDicListByName({ name: v });
      if (!data || !data.length) {
        this[type == 'big' ? 'smallList' : 'fineList'] = [];
        return;
      }
      let list = data.map((item) => Object.assign({}, { label: item.dic_value, value: item.flag }));
      this[type == 'big' ? 'smallList' : 'fineList'] = [].concat(list);
    },
    async getDicAsync() {
      const data = this.handleCommonResult(await msgNoticeDic({ name: 'D0137' }));
      if (data && data.length) {
        this.dicObj = data.reduce((res, item) => {
          return Object.assign({}, res, { [item.flag]: item.dic_value });
        }, {});
      }
    },
    async getDataAsync(params) {
      if (!params.message_people_id) return;
      return this.handleTableResult(await msgList(params));
    },
    async clearMsg() {
      Modal.confirm({
        title: '提示',
        content: '确认全部标记为已读',
        onOk: async () => {
          const params = { id: this.accountId };
          const res = await msgNoticeAllRead(params);
          if (res && res.code === 200) {
            this.setUnreadMsgNum(0);
            this.$message.success('全部标记成功！');
            this.$refs.table.load();
          } else {
            this.$message.error(res.msg || '全部标记失败！');
          }
        },
      });
    },
    async markMsgAsRead(params) {
      const res = await msgNoticeRead(params);
      if (res && res.code === 200) {
        this.$refs.table.load();
        this.setUnreadMsgNum(-1);
        return true;
      }
    },
    async markMultiMsgAsRead() {
      if (!this.selectedRowKeys.length) {
        return this.$message.error('请至少选择一个消息');
      }
      const ok = await this.markMsgAsRead({
        id: this.selectedRowKeys.join(','),
      });
      ok ? this.$message.success('批量标记成功') : this.$message.error('批量标记失败');
    },
    setUnreadMsgNum(num) {
      this.$vbus.$emit('updateHeadMsgNum', num);
    },
    async details(scope) {
      const { id, status, thirdparty_id, big_type, fine_type, small_type } = scope;
      const dataId = thirdparty_id;
      //点击详情之前 - 标记为已读
      if (status == 0) {
        await msgNoticeRead({ id });
      }
      // D0137_5 - 通知消息 - 公告、政策法规
      // if (small_type == 'D0137_5_1' || small_type == 'D0137_5_2_1') {
      //   // openContentDetailDialog({ id: dataId });
      //   return false;
      // }
      // 自建房 - 指令
      if (small_type == 'D0137_4_2') {
        openInstructionDetailsDialog({ id: dataId, canIExportDetails: false });
        return;
      }
      // D0137_4 - 任务消息 - 事件
      if (small_type == 'D0137_4_1') {
        this.showEventDetail({ event_id: dataId });
        return;
      }
      // 设备
      // D0137_3_4_3烟感告警 D0137_3_4_10高空抛物
      if (['D0137_3_4_3', 'D0137_3_4_10', 'D0137_3_4_14', 'D0137_3_4_15', 'D0137_3_4_16'].includes(fine_type)) {
        showYanGanWarnDialog({ id: dataId, sendReport: fine_type, fine_type: fine_type }, () => {
          this.$refs.table.load();
        });
        return;
      }
      // 其他设备
      if (small_type == 'D0137_3_4') {
        showDeviceWarnDialog(dataId);
        return;
      }
      dialog({
        content: () => import('./msg-notice-details.vue'),
        contentProps: {
          id,
        },
        dialogProps: {
          title: '详情',
          footer: null,
          bodyStyle: { padding: 0 },
        },
      });
    },
    showEventDetail({ event_id }) {
      openEventDetailsDialog(event_id).then(() => {
        this.$refs.table.load();
      });
    },
  },
};
</script>

<style scoped lang="less">
.msg-table {
  width: 100%;
  height: 100%;
  position: relative;
  .msg-type {
    padding: 5px 10px;
    display: flex;
    align-items: center;
    &-label {
      white-space: nowrap;
    }
  }
  .bottom-btn {
    position: absolute;
    bottom: 10px;
    left: 20px;
  }
}
</style>
